/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.SafetyPualificationBean;
import com.koron.purpose.mapper.SafetyPualificationMapper;
import com.koron.purpose.service.api.SafetyPualificationService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.purpose.utils.PdfFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@SuppressWarnings("deprecation")
@Service
public class SafetyPualificationServiceImpl implements SafetyPualificationService {

    private final Logger logger = LoggerFactory.getLogger(SafetyPualificationServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Autowired
    private PdfFileUtil pdfFileUtil;

    @Override
    public MessageBean<DataBean<Map>> queryForList(String wcorpCode, String corpName, String pualificationType,
                                                   String acquisitionTimeStart, String acquisitionTimeStop,
                                                   Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("wcorpCode", wcorpCode);
            map.put("corpName", corpName);
            map.put("pualificationType", pualificationType);
            map.put("acquisitionTimeStart", acquisitionTimeStart);
            map.put("acquisitionTimeStop", acquisitionTimeStop);
            page = (page == null || page < 1) ? 1 : page;
            pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
            int pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            List<Map> list = mapper.queryForList(map);
            DataBean<Map> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            // 总条数
            Integer totalNumber = mapper.countForList(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public List<Map> queryForList(String wcorpCode, String corpName, String pualificationType, String acquisitionTimeStart, String acquisitionTimeStop) {
        List<Map> list = null;
        try (SessionFactory factory = new SessionFactory()) {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            Map map = new HashMap();
            map.put("wcorpCode", wcorpCode);
            map.put("corpName", corpName);
            map.put("pualificationType", pualificationType);
            map.put("acquisitionTimeStart", acquisitionTimeStart);
            map.put("acquisitionTimeStop", acquisitionTimeStop);
            list = mapper.queryForList(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            SafetyPualificationBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("未查到该安全资质");
            } else {
                msg.setData(bean);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean insertSafetyPuali(StaffBean user, SafetyPualificationBean bean, MultipartFile[] files) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(bean.getWcorpCode()) || StringUtils.isEmpty(bean.getWcorpName())
                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || StringUtils.isEmpty(bean.getPualificationType()) || StringUtils.isEmpty(bean.getPualificationTypeName())
                || StringUtils.isEmpty(bean.getCredentialName()) || bean.getAcquisitionTime() == null || null == bean.getEffectiveTime()) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            // 附件保存
            if (files == null) {
                bean.setAccessorys("");
            } else {
                JSONArray array = new JSONArray();
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    String filename = file.getOriginalFilename();
                    int index = filename.lastIndexOf(".");
                    String filetype = filename.substring(index + 1).toLowerCase();
                    if ("pdf".equals(filetype)) {
                        object.put("pdfUrl", object.get("fileUrl"));
                    } else {
                        object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    }
                    array.add(object);
                }
                bean.setAccessorys(JSON.toJSONString(array));
            }
            Date date = new Date();
            bean.setAddTime(date);
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            mapper.insertSafetyPualifi(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean updateSafetyPuali(StaffBean user, SafetyPualificationBean bean, MultipartFile[] files) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        SessionFactory factory = new SessionFactory();
        try {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            // 根据id 查询 安全会议
            SafetyPualificationBean safetyPualificationBean = mapper.queryById(bean.getId());
            if (safetyPualificationBean == null) {
                msg.setCode(35002);
                msg.setDescription("参数校验异常");
                factory.close(false);
                return msg;
            }
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            // 删除附件
            String accessorysStr = safetyPualificationBean.getAccessorys();
            if (!StringUtils.isEmpty(accessorysStr)) {
                List<Map> meetingRecords_old = JSON.parseArray(accessorysStr, Map.class);
                List<Map> meetingRecords_new = null;
                if (!StringUtils.isEmpty(bean.getAccessorys())) {
                    meetingRecords_new = JSON.parseArray(bean.getAccessorys(), Map.class);
                    for (Map map : meetingRecords_old) {
                        if (!filter(map, meetingRecords_new, "fileUrl")) {// 不存在:删除文件
                            Optional.ofNullable(map.get("fileUrl")).ifPresent(u -> {
                                if (!StringUtils.isEmpty(u.toString())) {
                                    fastDFSClientWrapper.deleteFile(u.toString());
                                }
                            });
                            Optional.ofNullable(map.get("pdfUrl")).ifPresent(u -> {
                                if (!StringUtils.isEmpty(u.toString())) {
                                    fastDFSClientWrapper.deleteFile(u.toString());
                                }
                            });
                        }
                    }
                }
            }
            String str = "";
            // 附件保存
            if (files != null) {
                JSONArray array;
                if (!StringUtils.isEmpty(bean.getAccessorys())) {
                    array = JSON.parseArray(bean.getAccessorys());
                } else {
                    array = new JSONArray();
                }
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    String filename = file.getOriginalFilename();
                    int index = filename.lastIndexOf(".");
                    String filetype = filename.substring(index + 1).toLowerCase();
                    if ("pdf".equals(filetype)) {
                        object.put("pdfUrl", object.get("fileUrl"));
                    } else {
                        object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    }
                    array.add(object);
                }
                str = JSON.toJSONString(array);
                bean.setAccessorys(str);
                mapper.updateSafetyPualifi(bean);
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
        }
        return msg;
    }

    @Override
    public MessageBean deleteSafetyPualiById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyPualificationMapper mapper = factory.getMapper(SafetyPualificationMapper.class);
            SafetyPualificationBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该安全资质已被删除");
                factory.close(false);
                return msg;
            }
            int i = mapper.deleteSafetyPualifiById(id);
            if (i != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("删除失败!");
                factory.close(false);
            } else {
                factory.close();
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    /**
     * 判断map中的 key是否在list中存在
     *
     * @param map
     * @param list
     * @param key
     * @return
     */
    private boolean filter(Map<String, String> map, List<Map> list, String key) {
        String str = map.get(key);
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        if (list == null || list.size() == 0) {
            return false;
        }
        for (Map m : list) {
            if (str.equals(Optional.ofNullable(m.get(key)).get().toString())) {
                return true;
            }
        }
        return false;
    }
}
